package com.frxuexi.park2209.user

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.blankj.utilcode.util.EncryptUtils
import com.blankj.utilcode.util.RegexUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.frxuexi.base.entity.UserBean
import com.frxuexi.base.mvvm.BaseActivity
import com.frxuexi.base.net.Const
import com.frxuexi.park2209.MainActivity
import com.frxuexi.park2209.R
import com.frxuexi.park2209.databinding.ActivityLoginBinding
import com.google.gson.Gson
import dagger.hilt.android.AndroidEntryPoint
import java.lang.StringBuilder

@AndroidEntryPoint
class LoginActivity : BaseActivity<ActivityLoginBinding,LoginViewModel>() {

    override fun initData() {
        vm.loginSuccess.observe(this){
//            val userBean = Gson().fromJson(it, UserBean::class.java)
            val userBean = it
//            Log.i("===",json.toString())
            SPUtils.getInstance().put(Const.TOKEN,userBean.token)
            SPUtils.getInstance().put(Const.UNAME,userBean.uName)
            SPUtils.getInstance().put(Const.UID,userBean.uId!!)

            ToastUtils.showLong("登录成功")

            startActivity(Intent(this@LoginActivity,MainActivity::class.java))
            finish()
        }
    }

    override fun initView() {

        val token = SPUtils.getInstance().getString("token", "")
        if(!token.isNullOrEmpty()){
            startActivity(Intent(this@LoginActivity,MainActivity::class.java))
            finish()
            return
        }

        binding.tvRegister.setOnClickListener {
            startActivity(Intent(this@LoginActivity,RegisterActivity::class.java))
        }

        binding.btnLogin.setOnClickListener {
            val uname = binding.etName.text.toString()
            val upass = binding.etPass.text.toString()

            if(uname.isNullOrEmpty() || upass.isNullOrEmpty()){
                ToastUtils.showLong("输入内容不能为空")
                return@setOnClickListener
            }

            if(!uname.matches(Regex("[0-9A-z]{2,10}"))){
                ToastUtils.showLong("不是合法用户名")
                return@setOnClickListener
            }

            val map = mutableMapOf<String, String>()
            val time = (System.currentTimeMillis() / 1000).toString()

            val sb = StringBuilder()
            sb.append(uname).append(upass).append(time).append("tamboo")

            val sign = EncryptUtils.encryptMD5ToString(sb.toString()).toLowerCase()

            map["uName"]=uname
            map["uPwd"]=upass
            map["time"]=time
            map["sign"]=sign
            vm.login(map)

        }
    }
}